<template>
  <div class="product-list">
    <div class="filters">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索商品"
        @input="handleSearch"
      />
      <el-select v-model="sortBy" @change="handleSort">
        <el-option label="价格从低到高" value="price_asc" />
        <el-option label="价格从高到低" value="price_desc" />
        <el-option label="销量优先" value="sales" />
      </el-select>
    </div>
    
    <div class="products">
      <div v-for="product in products" :key="product.id" class="product-card">
        <el-image :src="product.imageUrl" fit="cover" />
        <h3>{{ product.name }}</h3>
        <p class="price">¥{{ product.price }}</p>
        <p class="stock">库存: {{ product.stock }}</p>
        <el-button type="primary" @click="addToCart(product)">
          加入购物车
        </el-button>
      </div>
    </div>
    
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

const store = useStore()
const products = ref([])
const searchKeyword = ref('')
const sortBy = ref('price_asc')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const loadProducts = async () => {
  try {
    const response = await store.dispatch('product/getProducts', {
      page: currentPage.value - 1,
      size: pageSize.value,
      keyword: searchKeyword.value,
      sort: sortBy.value
    })
    products.value = response.content
    total.value = response.totalElements
  } catch (error) {
    ElMessage.error('加载商品列表失败')
  }
}

const addToCart = async (product) => {
  try {
    await store.dispatch('cart/addToCart', {
      productId: product.id,
      quantity: 1
    })
    ElMessage.success('已添加到购物车')
  } catch (error) {
    ElMessage.error('添加购物车失败')
  }
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.product-list {
  padding: 20px;
}

.filters {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.products {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  border: 1px solid #eee;
  padding: 10px;
  text-align: center;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.stock {
  color: #666;
  font-size: 14px;
}
</style> 